package cn.yzj.openapi.service.impl;

import cn.yzj.openapi.dto.EmailDTO;
import cn.yzj.openapi.service.EmailService;
import cn.yzj.openapi.utils.NanoIdUtils;
import com.google.common.cache.Cache;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * Email 服务实现类
 *
 * @author gzkemays
 * @since 2022/4/15 17:37
 */
@Service
public class EmailServiceImpl implements EmailService {
  @Resource JavaMailSender mailSender;

  @Resource(name = "emailCache")
  Cache<String, Object> emailCache;

  @Override
  public String sendVerificationCode(EmailDTO dto) {
    dto.setCode(NanoIdUtils.randomNanoId(6));
    Object ifPresent = emailCache.getIfPresent(dto.getTo());
    if (ifPresent != null) {
      dto.setCode(ifPresent.toString());
      return sendCode(dto);
    }
    return sendCode(dto);
  }

  @Override
  public void send(EmailDTO dto) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    try {
      message.setFrom(new InternetAddress("椰子鸡工作室 <yezijigroup@qq.com>"));
      message.setTo(dto.getTo());
      message.setSentDate(new Date());
      message.setSubject(dto.getSubject());
      message.setText(dto.getMessage(), true);
      mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }

  public String sendCode(EmailDTO dto) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    String to = dto.getTo();
    String code = dto.getCode();
    try {
      String text =
          "    <div style=\"width: 200px;border: 1px solid black;padding: 10px;position: relative;text-align: center;\">\n"
              + "        <span>\n"
              + "            验证码：<span style=\"font-weight: 800;color:red;\">"
              + dto.getCode()
              + "</span>\n"
              + "        </span>\n"
              + "    </div>";
      if (dto.getAdditional() != null) {
        text = dto.getAdditional() + text;
      }
      message.setFrom(new InternetAddress("椰子鸡工作室 <yezijigroup@qq.com>"));
      message.setTo(to);
      message.setSentDate(new Date());
      message.setSubject(dto.getSubject());
      message.setText(text, true);
      mailSender.send(message.getMimeMessage());
      emailCache.put(to, code);
      return code;
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    return code;
  }
}
